import { login, logout, getInfo } from '@/api/admin'
import { getLoginUser } from '@/api2/partyManage'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'
import data from '@/data'
import { websock } from '@/websock'
// import md5 from 'js-md5'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, platform } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone: username.trim(), password: password, platform: platform}).then(response => {
        console.log('action login', response)
        commit('SET_TOKEN', response)
        commit('SET_NAME', '')
        commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80')
        data.token = response
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  info({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        if (!response) {
          return reject('Verification failed, please Login again.')
        }
        const { name, avatar } = response
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  djPermission({ dispatch }) {
    return new Promise(async (resolve, reject) => {
      const info = await dispatch('info')
      const { data } = await getLoginUser();

      info.djDeptId = data.djDeptId;
      info.permission = data.permission;
      sessionStorage.setItem("loginUserinfo", JSON.stringify(info));

      sessionStorage.setItem("isNotice", data.isNotice ? 1 : 0);

      const djRoutes = constantRoutes.reduce((a, n) => {
        if (n.path === '/partyManage') {
          a = n.children.map(item => {
            return item.path
          })
        }
        return a
      }, [])
      const routes = !data.permission || data.permission === 'common' ? [] : djRoutes
      resolve(routes)
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        websock.disconnect()
        data.userInfo = null
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

